package com.seocoo.worker.order;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jaeger.library.StatusBarUtil;
import com.seocoo.worker.R;
import com.seocoo.worker.base.KeyboardUtil;
import com.seocoo.worker.base.multiImage.BaseListImageFragment;
import com.seocoo.worker.base.multiImage.RspImage;
import com.seocoo.worker.base.widget.AppToolBer;
import com.seocoo.worker.friend.entity.RxEvaluateSuccess;
import com.seocoo.worker.order.entity.EMeasureDetail;
import com.seocoo.worker.order.entity.EMeasureInit;
import com.seocoo.worker.order.entity.Edict;
import com.seocoo.worker.order.entity.RspGoodsMeasureInfo;
import com.seocoo.worker.order.model.OrderModel;
import com.seocoo.worker.order.req.ReqGoodsMeasureInfo;
import com.seocoo.worker.order.req.ReqOrderMeasure;
import com.seocoo.worker.order.widget.adapter.OrderGoldMeasureAdapter;
import com.sfh.lib.event.BusEventManager;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.MVVMActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * author : Ssp
 * date   : 2020/2/22 23:54
 * desc   : 录入测量信息
 */
public class OrderGoldMeasureActivity extends MVVMActivity implements OnClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private AppToolBer appToolBer;
    private String orderId;
    private RecyclerView recycler_view;
    private EditText et_remark;
    private OrderGoldMeasureAdapter adapter;
    private TextView tv_receiving;
    private TextView tv_max_remark;
    private TextView tv_cancel;
    private EMeasureInit mDatas;
    private BaseListImageFragment upLoadFileFragment;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderGoldMeasureActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_gold_measure_activity);
        orderId = getIntent().getStringExtra("orderId");
        initView();
        initListener();
        StatusBarUtil.setTranslucentForImageView(this, 0, appToolBer);
        reFreshData();
    }

    private void reFreshData() {
        getViewModel(OrderModel.class).getOrderMeasureInfo(new ReqGoodsMeasureInfo(orderId));
        getViewModel(OrderModel.class).queryMeasureInit();
    }

    @LiveDataMatch
    public void onMeasureInit(EMeasureInit data) {
        mDatas = data;
    }

    @LiveDataMatch
    public void onGetMeasureInfoSuccess(List<RspGoodsMeasureInfo> data) {
        if (data == null) {
            return;
        }
        if (data.size() == 0) {
            return;
        }
        adapter.setNewData(data);
    }

    private void initView() {
        appToolBer = findViewById(R.id.appToolBer);
        recycler_view = findViewById(R.id.recycler_view);
        et_remark = findViewById(R.id.ev_remark);
        tv_max_remark = findViewById(R.id.tv_max_remark);
        et_remark.setFilters(new InputFilter[]{new InputFilter.LengthFilter(200)});
        et_remark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_max_remark.setText(s.length() + "/200");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tv_receiving = findViewById(R.id.tv_receiving);
        tv_cancel = findViewById(R.id.tv_cancel);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderGoldMeasureAdapter();
        adapter.bindToRecyclerView(recycler_view);
        adapter.setOnItemChildClickListener(this);
        recycler_view.setAdapter(adapter);
        upLoadFileFragment = (BaseListImageFragment) getSupportFragmentManager().findFragmentById(R.id.upLoadFileFragment);
        assert upLoadFileFragment != null;
        upLoadFileFragment.setImageCount(3, 6, true);
        upLoadFileFragment.setTv_title1("现场图片上传");
        upLoadFileFragment.setTv_title2("最多可上传6张图片");
        RspImage rspImage = new RspImage();
        rspImage.setFullPath("-1");
        ArrayList<RspImage> list = new ArrayList<>();
        list.add(rspImage);
        upLoadFileFragment.setNewData(list);
    }

    private void initListener() {
        tv_cancel.setOnClickListener(this);
        tv_receiving.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_receiving:
                String evRemarkText = et_remark.getText().toString();
                if (TextUtils.isEmpty(evRemarkText)) {
                    evRemarkText = "";
                }
                getReqOrderMeasure(evRemarkText);
                break;
            default:
                break;
        }
    }

    public void getReqOrderMeasure(String evRemarkText) {
        ReqOrderMeasure reqOrderMeasure = new ReqOrderMeasure();
        reqOrderMeasure.remark = evRemarkText;
        reqOrderMeasure.orderId = orderId;
        reqOrderMeasure.measureDetail = new ArrayList<>();
        List<RspGoodsMeasureInfo> data = adapter.getData();
        for (int i = 0; i < data.size(); i++) {
            RspGoodsMeasureInfo info = data.get(i);
            EMeasureDetail eMeasureDetail = new EMeasureDetail();
            eMeasureDetail.goodsId = info.getGoodsId();

            EditText et_jx_area = (EditText) adapter.getViewByPosition(i, R.id.et_jx_area);
            assert et_jx_area != null;
            String trim1 = et_jx_area.getText().toString().trim();
            if (TextUtils.isEmpty(trim1)) {
                showToast("请输入测量数据");
                return;
            }
            eMeasureDetail.recArea = trim1;
            EditText et_yx_area = (EditText) adapter.getViewByPosition(i, R.id.et_yx_area);
            assert et_yx_area != null;
            String et_yx_area1 = et_yx_area.getText().toString().trim();
            if (!TextUtils.isEmpty(et_yx_area1)) {
                eMeasureDetail.abnormityArea = et_yx_area1;
            }
            EditText et_zj_area = (EditText) adapter.getViewByPosition(i, R.id.et_zj_area);
            assert et_zj_area != null;
            String et_zj_area1 = et_zj_area.getText().toString().trim();
            if (!TextUtils.isEmpty(et_zj_area1)) {
                eMeasureDetail.cornerMeter = et_zj_area1;
            }
            EditText et_sx_num = (EditText) adapter.getViewByPosition(i, R.id.et_sx_num);
            assert et_sx_num != null;
            String etSum = et_sx_num.getText().toString().trim();
            if (TextUtils.isEmpty(etSum)) {
                showToast("请输入扇数量");
                return;
            }
            eMeasureDetail.fanCount = etSum;
            EditText et_money = (EditText) adapter.getViewByPosition(i, R.id.et_money);
            assert et_money != null;
            String money = et_money.getText().toString().trim();
            if (!TextUtils.isEmpty(money)) {
                eMeasureDetail.otherCost = money;
            }
            TextView tv_select_glass_color = (TextView) adapter.getViewByPosition(i, R.id.tv_select_glass_color);
            assert tv_select_glass_color != null;
            String glassColor = tv_select_glass_color.getText().toString().trim();
            if (TextUtils.isEmpty(glassColor)) {
                showToast("请选择玻璃规格");
                return;
            }
            eMeasureDetail.glassSpecification = info.getGlassSpecification();
            eMeasureDetail.glassSpecificationDesc = glassColor;
            TextView tv_door_color1 = (TextView) adapter.getViewByPosition(i, R.id.tv_door_color1);
            assert tv_door_color1 != null;
            String color1Text = tv_door_color1.getText().toString().trim();
            if (TextUtils.isEmpty(color1Text)) {
                showToast("请选择内色");
                return;
            }
            eMeasureDetail.insideColor = color1Text;
            TextView tv_door_color2 = (TextView) adapter.getViewByPosition(i, R.id.tv_door_color2);
            assert tv_door_color2 != null;
            String color2Text = tv_door_color2.getText().toString().trim();
            if (TextUtils.isEmpty(color2Text)) {
                showToast("请选择外色");
                return;
            }
            eMeasureDetail.outsideColor = color2Text;
            reqOrderMeasure.measureDetail.add(eMeasureDetail);
        }
        List<RspImage> imgList = upLoadFileFragment.getImgList();
        int size = imgList.size();
        if (size > 0) {

            StringBuilder imgUrl = new StringBuilder();
            for (int i = 0; i < size; i++) {

                RspImage rspImage = imgList.get(i);
                if (!TextUtils.equals("-1", rspImage.getFullPath())) {
                    String fileName = rspImage.getFileName();
                    imgUrl = imgUrl.append(fileName).append(",");
                }

            }

            if (imgUrl.toString().endsWith(",")) {
                reqOrderMeasure.measurePic = imgUrl.substring(0, imgUrl.length() - 1);
            } else {
                reqOrderMeasure.measurePic = imgUrl.toString();
            }
        }

        getViewModel(OrderModel.class).addOrderMeasure(reqOrderMeasure);
    }

    @LiveDataMatch
    public void onAddOrderMeasure() {
        RxEvaluateSuccess success = new RxEvaluateSuccess();
        success.setSuccess(true);
        BusEventManager.postEvent(success);
        finish();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        KeyboardUtil.hideKeyboard(view);
        if (mDatas == null) return;
        switch (view.getId()) {
            case R.id.tv_door_color1:
                String selectType = "1";
                showSelectDialog(mDatas.glassInColor, position, selectType, "选择内色");
                break;
            case R.id.tv_door_color2:
                selectType = "2";
                showSelectDialog(mDatas.glassOutColor, position, selectType, "选择外色");
                break;
            case R.id.tv_select_glass_color:
                selectType = "3";
                showSelectDialog(mDatas.glassMatch, position, selectType, "选择玻璃规格");
                break;
            default:
                break;

        }
    }

    private void showSelectDialog(List<Edict> data, int position, String selectType, String title) {

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            Edict edict = data.get(options1);
            if (TextUtils.equals("1", selectType)) {
                adapter.setColor1(position, edict.dictLabel);
            }
            if (TextUtils.equals("2", selectType)) {
                adapter.setColor2(position, edict.dictLabel);
            }
            if (TextUtils.equals("3", selectType)) {
                adapter.setGlass(position, edict);
            }
        }).build();
        if (data == null) {
            return;
        }
        ArrayList<String> list = new ArrayList<>();
        for (Edict bean : data) {
            list.add(bean.dictLabel);
        }
        pvOptions.setPicker(list);
        pvOptions.setTitleText(title);
        pvOptions.show();
    }
}
